package 排序;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;

public class 优先队列排序 {

    private static class Customer {

        private Integer id;

        private String name;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Customer(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        public Customer() {
        }

        @Override
        public String toString() {
            return  "weight=" + id +
                    ", name=" + name;
        }

    }

    public static void main(String[] args) {
        // 1.演示优先队列的自然排序
        Queue<Integer> naturePriorityQueue = new PriorityQueue<>(10);
        for (int i = 0; i < 10; i++) {
            int random = (int) (Math.random() * 100000 + 1);
            System.out.println("add i value = " + random);
            naturePriorityQueue.add(random);
            Integer peek = naturePriorityQueue.peek();
            System.out.println("poll i value = " + peek);
            System.out.println();

        }


        // 2.演示自定义排序
        Queue<Customer> customerPriorityQueue = new PriorityQueue<>(10, idComparator);// 初始化队列大小并指定比较器

        for (int i = 0; i < 10; i++) {
            Customer customer = new Customer((int) (Math.random() * 6532 + 1), "customer" + i);
            System.out.println("add customer is " + customer.toString());
            customerPriorityQueue.add(customer);
            Customer customer1 = customerPriorityQueue.peek();
            System.out.println("peek customer is " + customer1.toString());
            System.out.println();
        }

    }

    // 自定义的比较器
    public static Comparator<Customer> idComparator = new Comparator<Customer>() {
        @Override
        public int compare(Customer o1, Customer o2) {
            return o1.getId() - o2.getId();
        }
    };

}
